﻿using EOM.TSHotelManagement.Shared;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace EOM.TSHotelManagement.Common.Util
{
    public class JWTHelper
    {
        /// <summary>
        /// JWT加密
        /// </summary>
        private readonly IJwtConfigFactory _jwtConfigFactory;

        public JWTHelper(IJwtConfigFactory jwtConfigFactory)
        {
            _jwtConfigFactory = jwtConfigFactory;
        }

        public string GenerateJWT(string account)
        {
            var jwtConfig = _jwtConfigFactory.GetJwtConfig();
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(jwtConfig.Key);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, account)
                }),
                Expires = DateTime.Now.AddMinutes(jwtConfig.ExpiryMinutes),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                Audience = jwtConfig.Audience,
                Issuer = jwtConfig.Issuer
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}
